<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Contact extends MX_Controller {

	private $module = 'contact';
	private $table = 'contact';
	function __construct(){
		parent::__construct();
		$this->load->model($this->module.'_model','model');
		$this->load->model('admincp_modules/admincp_modules_model');
		if($this->uri->segment(1)=='admincp'){
			if($this->uri->segment(2)!='login'){
				if(!$this->session->userdata('userInfo')){
					header('Location: '.PATH_URL.'admincp/login');
					return false;
				}
				$get_module = $this->admincp_modules_model->check_modules($this->uri->segment(2));
				$this->session->set_userdata('ID_Module',$get_module[0]->id);
				$this->session->set_userdata('Name_Module',$get_module[0]->name);
			}
			$this->template->set_template('admin');
			$this->template->write('title','Admin Control Panel');
		}
	}
	/*------------------------------------ Admin Control Panel ------------------------------------*/
	public function admincp_index(){
		modules::run('admincp/chk_perm',$this->session->userdata('ID_Module'),'r',0);
		$default_func = 'created';
		$default_sort = 'DESC';
		$data = array(
			'module'=>$this->module,
			'module_name'=>$this->session->userdata('Name_Module'),
			'default_func'=>$default_func,
			'default_sort'=>$default_sort
		);
		$this->template->write_view('content','BACKEND/index',$data);
		$this->template->render();
	}


	public function admincp_update($id=0){
		$result[0] = array();
		if($id!=0){
			$result = $this->model->getDetailManagement($id);
		}

		$data = array(
			'result'=>$result[0],
			'module'=>$this->module,
			'id'=>$id,
		);
		$this->template->write_view('content','BACKEND/ajax_editContent',$data);
		$this->template->render();
	}

	public function admincp_save(){
		if($_POST){
			if($this->model->saveManagement()){

				print 'success';
				exit;
			}
		}
	}

	public function save_info_contact(){
		if($_POST){
			if($this->model->saveManagement()){
				$this->session->set_flashdata('success_lienhe', 'Bạn đã gửi thông tin thành công !');
				header('Location: '.PATH_URL.'lien-he.html');
			}
		}
	}

	public function admincp_delete(){
		if($this->input->post('id')){
			$id = $this->input->post('id');
			$result = $this->model->getDetailManagement($id);
			$this->db->where('id',$id);
			if($this->db->delete(PREFIX.$this->table)){
				//Xóa hình khi Delete
				return true;
			}
		}
	}

	public function admincp_ajaxLoadContent(){
		$this->load->library('AdminPagination');
		$config['total_rows'] = $this->model->getTotalsearchContent();
		$config['per_page'] = $this->input->post('per_page');
		$config['num_links'] = 3;
		$config['func_ajax'] = 'searchContent';
		$config['start'] = $this->input->post('start');
		$this->adminpagination->initialize($config);

		$result = $this->model->getsearchContent($config['per_page'],$this->input->post('start'));
		$data = array(
			'result'=>$result,
			'per_page'=>$this->input->post('per_page'),
			'start'=>$this->input->post('start'),
			'module'=>$this->module
		);
		$this->session->set_userdata('start',$this->input->post('start'));
		$this->load->view('BACKEND/ajax_loadContent',$data);
	}

	public function admincp_ajaxUpdateStatus(){
		if($this->input->post('status')==0){
			$status = 1;
		}else{
			$status = 0;
		}
		$data = array(
			'status'=>$status
		);
		$this->db->where('id', $this->input->post('id'));
		$this->db->update(PREFIX.$this->table, $data);

		$update = array(
			'status'=>$status,
			'id'=>$this->input->post('id'),
			'module'=>$this->module
		);
		$this->load->view('BACKEND/ajax_updateStatus',$update);
	}
	/*------------------------------------ End Admin Control Panel --------------------------------*/


	/*------------------------------------ FRONTEND ------------------------------------*/
	function index(){
		//create captcha
		$this->load->helper('captcha');
		$expiration = time()-7200; // Two hour limit
		$img_path = BASEFOLDER.'static/images/captcha/';
		$img_url = PATH_URL.'static/images/captcha/';
		$vals = array(
			'img_path' =>  $img_path,
			'img_url' => $img_url,
			'word'	  => random_string(5),
			'img_width'	 => '83',
    	'img_height' => '33',
			);

		$cap = create_captcha($vals);
		$data = array(
			'captcha_time'	=> $cap['time'],
			'ip_address'	=> getIP(),
			'word'	 => $cap['word']
		);
		$query = $this->db->insert_string(CAPTCHA_TB, $data);
		$this->db->query($query);

		$this->session->set_userdata('captcha', $cap['word']);
		$data['cap_img']=$cap['image'];
		$this->template->write_view('content','FRONTEND/contact',$data);
		$this->template->render();
	}
	public function contact_global(){
		//create captcha
		$this->load->helper('captcha');
		$expiration = time()-7200; // Two hour limit
		$img_path = BASEFOLDER.'static/images/captcha/';
		$img_url = PATH_URL.'static/images/captcha/';
		$vals = array(
			'img_path' =>  $img_path,
			'img_url' => $img_url,
			'word'	  => random_string(5),
			'img_width'	 => '83',
    	'img_height' => '33',
			);

		$cap = create_captcha($vals);
		$data = array(
			'captcha_time'	=> $cap['time'],
			'ip_address'	=> getIP(),
			'word'	 => $cap['word']
		);
		$query = $this->db->insert_string(CAPTCHA_TB, $data);
		$this->db->query($query);

		$this->session->set_userdata('captcha', $cap['word']);
		$data['cap_img']=$cap['image'];
		$this->load->view('FRONTEND/contact_global',$data);
	}
	public function send_contact(){
		// First, delete old captchas
		// $this->load->helper('captcha');
		// $expiration = time()-1800; // Two hour limit
		// $img_path = BASEFOLDER.'static/images/captcha/';
		// $img_url = PATH_URL.'static/images/captcha/';
		// $vals = array(
		// 	'img_path' =>  $img_path,
		// 	'img_url' => $img_url,
		// 	'word'	  => random_string(6),
		// 	'img_width'	 => '83',
  //   	'img_height' => '33',
		// 	);

		// $cap = create_captcha($vals);
		// $data = array(
		// 	'captcha_time'	=> $cap['time'],
		// 	'ip_address'	=> getIP(),
		// 	'word'	 => $cap['word']
		// );
		// $query = $this->db->insert_string(CAPTCHA_TB, $data);
		// $this->db->query($query);
		// $this->session->set_userdata('captcha', $cap['word']);
		// $this->db->query("DELETE FROM ".CAPTCHA_TB." WHERE captcha_time < ".$expiration);

		// First, delete old captchas

		//validate submitted data
		if (!empty($_POST)) {
			// if(!$this->check_captcha()){
			// 	print('incorrect_captcha');
			// 	exit();
			// }
			$expiration = time()-7200; // Two hour limit
			$this->db->query("DELETE FROM cli_captcha WHERE captcha_time < ".$expiration);

			// Then see if a captcha exists:
			$sql = "SELECT COUNT(*) AS count FROM cli_captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
			$binds = array($_POST['inp_captcha'], $this->input->ip_address(), $expiration);
			$query = $this->db->query($sql, $binds);
			$row = $query->row();

			if ($row->count == 0)
			{
		    print('incorrect_captcha');
				exit();
			}
			//send email
			$data_html = array(
				'name'	=> strtolower($this->input->post('co_name')),
				'phone'		=> $this->input->post('co_phone'),
				'address'	=> $this->input->post('co_address'),
			);
			$data_email = array(
				'data'	=>	$data_html,
				'mail_view'=>'FRONTEND/email/contact_success'
			);
			$email_content = $this->load->view('FRONTEND/email/E-letter', $data_email, TRUE);
			//pr($email_content,1);
			$data_email= array(
				'email'	=> $this->input->post('co_email'),
				'html'	=> $email_content,
				'subject'	=> 'Thông tin cần được hỗ trợ từ AN BÌNH CO'
			);

			$sent = $this->model->send_email($data_email);
			
			//end send email

      $id = $this->model->send_contact();
      if ($id) {
          print 1;
          exit;
      } else {
          print 0;
          exit;
      }
  	}
	}

	public function check_captcha()
	{
		$expiration = time()-7200; // Two hour limit
		print($this->session->userdata('captcha'));
		print('-');
		print($this->input->post('inp_captcha'));
		$cap=$this->input->post('inp_captcha');
		if($this->session->userdata('captcha') == $cap
		 AND $this->session->userdata('ip_address')== $this->input->ip_address()
		 AND $this->session->userdata('captcha_time')> $expiration)
		{
		 return true;
		}
		else{
		 //$this->form_validation->set_message('check_captcha', 'Security number does not match.');
		 return false;
		}
	}
	/*------------------------------------ End FRONTEND --------------------------------*/
}
